package Stack;

import java.util.ArrayList;

public class AchieveStackOfLinkList<T> {
    private MyNode<T> head;

    public AchieveStackOfLinkList() {
        this.head = new MyNode<>();
        head.data = null;
        head.next = null;
    }
    //判断栈是否为空
    boolean isEmpty() {
        return head == null;
    }
    //栈的大小
    int size() {
        int size = 0;
        MyNode<T> p = head.next;
        while (p != null) {
            p = p.next;
            size++;
        }
        return size;
    }

    void push(T e) {
        MyNode<T> temp = new MyNode<>();
        temp.data = e;
        temp.next = head.next;
        head.next = temp;
    }

    //出栈，同时返回栈顶元素
    T pop() {
        MyNode<T> temp = head.next;
        if (temp != null) {
            head.next = temp.next;
            return temp.data;
        }
        System.out.println("占中已经不存元素了");
        return null;
    }

    //获取栈顶元素
    T top() {
        if (head.next != null) {
            return head.next.data;
        }
        System.out.println("栈中不存在元素");
        return null;
    }

    public static void main(String[] args) {
        AchieveStackOfLinkList<Integer> stackDemo = new AchieveStackOfLinkList();
        stackDemo.push(1);
        stackDemo.push(3);
        stackDemo.push(5);

        System.out.println("栈顶元素：" + stackDemo.top());
        System.out.println("栈大小：" + stackDemo.size());

        stackDemo.pop();
        System.out.println("栈第一次弹出元素");

        stackDemo.pop();
        System.out.println("栈第二次弹出元素");

        stackDemo.pop();
        System.out.println("栈第二次弹出元素");

        stackDemo.pop();

    }
}

class MyNode<T> {
    T data;
    MyNode<T> next;
}
